import 'dart:async';
import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sp_util/sp_util.dart';
import 'package:workmate/app.dart';
import 'package:workmate/widget/feedback.dart';

void main() async {
  debugPrint('启动APP...');

  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  await initGlobal();
  initGlobalException();
  runZonedGuarded(
    () {
      runApp(EasyLocalization(
          startLocale: const Locale('zh', 'CN'),
          supportedLocales: const [
            Locale('en'),
            Locale('zh', 'CN'),
          ],
          path: 'assets/locale',
          child: const Application()));
      if (Platform.isAndroid) {
        // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
        SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
        );
        SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
      }
      debugPrint('启动APP完成');
    },
    (error, stackTrace) {
      debugPrint(error.toString());
    },
    zoneSpecification: ZoneSpecification(
        print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
      parent.print(self, line);
    }),
  );
}

// 前置初始化
Future initGlobal() async {
  await SpUtil.getInstance();
}

// 全局页面报错
initGlobalException() {
  ErrorWidget.builder = (FlutterErrorDetails flutterErrorDetails) {
    debugPrint(flutterErrorDetails.toString());
    return const FeedbackWidget();
  };

  // 全局错误
  FlutterError.onError = (FlutterErrorDetails details) async {
    debugPrint(details.toString());
  };
}
